package com.iotechn.unimall.app.api.plantgoods;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.iotechn.unimall.data.domain.AreaDO;
import com.iotechn.unimall.data.domain.PlantGoodsDO;
import com.iotechn.unimall.data.domain.PlantGoodsLogDO;
import com.iotechn.unimall.data.domain.UserShopDO;
import com.iotechn.unimall.data.dto.plantgood.PlantGoodDetailDTO;
import com.iotechn.unimall.data.enums.SystemStatusType;
import com.iotechn.unimall.data.mapper.AreaMapper;
import com.iotechn.unimall.data.mapper.PlantGoodsLogMapper;
import com.iotechn.unimall.data.mapper.PlantGoodsMapper;
import com.iotechn.unimall.data.mapper.UserShopMapper;
import com.iotechn.unimall.data.model.Page;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class PlantGoodsServiceImpl implements PlantGoodsService {

    @Autowired
    private PlantGoodsMapper plantGoodsMapper;

    @Autowired
    private AreaMapper areaMapper;

    @Autowired
    private PlantGoodsLogMapper plantGoodsLogMapper;

    @Autowired
    private UserShopMapper userShopMapper;

    @Override
    public Object selectGoodsByUser(Long userId) throws Exception {
        List<PlantGoodsDO> plantGoodsDOs = plantGoodsMapper.selectList(new EntityWrapper<PlantGoodsDO>().eq("status", 0).eq("user_id", userId).orderBy("gmt_update", false));
        return plantGoodsDOs;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object insertGood(String title, Double price, String img, Double stock, Long categoryId, Double yield, String unit, String lgla, String address, String street, Long areaId, String contactName, String contactPhone, Long userId) throws Exception {
        Date now = new Date();
        PlantGoodsDO plantGoods = new PlantGoodsDO();
        plantGoods.setTitle(title);
        plantGoods.setPrice(price);
        plantGoods.setImg(img);
        plantGoods.setStock(stock);
        plantGoods.setCategoryId(categoryId);
        plantGoods.setYield(yield);
        plantGoods.setUnit(unit);
        plantGoods.setStatus(SystemStatusType.ENABLE.getCode());
        plantGoods.setGmtUpdate(now);
        plantGoods.setGmtCreate(now);
        plantGoods.setLgla(lgla);
        plantGoods.setAddress(address);
        plantGoods.setStreet(street);
        plantGoods.setAreaId(areaId);
        if (areaId != null) {
            AreaDO areaDO = areaMapper.selectById(areaId);
            if (areaDO != null) {
                plantGoods.setArea(areaDO.getAreaName());
            }
        }
        plantGoods.setContactName(contactName);
        plantGoods.setContactPhone(contactPhone);
        plantGoods.setUserId(userId);
        return plantGoodsMapper.insert(plantGoods);
    }

    public Object getGoodsById(Long goodsId) throws Exception {
        PlantGoodsDO plantGoodsDO = plantGoodsMapper.selectById(goodsId);
        return plantGoodsDO;

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object saveCurrPriceAndStock(Long goodId, Double yield, String title, String contactName,
                                        String contactPhone, String curUnit, Double curPrice, Double currStock, Long userId) throws Exception {
        Date now = new Date();
        PlantGoodsDO plantGoodsDO = plantGoodsMapper.selectById(goodId);
        Double stock = plantGoodsDO.getStock();
        plantGoodsDO.setStock(currStock);
        plantGoodsDO.setTitle(title);
        plantGoodsDO.setUnit(curUnit);
        plantGoodsDO.setYield(yield);
        plantGoodsDO.setPrice(curPrice);
        plantGoodsDO.setContactName(contactName);
        plantGoodsDO.setContactPhone(contactPhone);
        plantGoodsDO.setGmtUpdate(now);
        System.out.println("plantGoodsDO.getUnit()==" + plantGoodsDO.getUnit());
        System.out.println("curUnit==" + curUnit);
        System.out.println("getGmtUpdate==" + plantGoodsDO.getGmtUpdate());
        System.out.println("currStock==" + currStock);
        System.out.println("plantGoodsDO.getStock()==" + plantGoodsDO.getStock());
        /*PlantGoodsDO plantGoodsDOnew = new PlantGoodsDO();
        plantGoodsDOnew.setUnit(curUnit);
        plantGoodsDOnew.setStock(currStock);
        plantGoodsDOnew.setId(goodId);
        plantGoodsDOnew.setGmtUpdate(now);*/
        plantGoodsMapper.updateById(plantGoodsDO);
        PlantGoodsLogDO log = new PlantGoodsLogDO();
        log.setGmtCreate(now);
        log.setGmtUpdate(now);
        log.setOrigStock(stock);
        log.setCurrStock(currStock);
        //log.setOrigPrice(price);
        //log.setCurrPrice(currPrice);
        log.setGoodId(plantGoodsDO.getId());
        log.setGoodName(plantGoodsDO.getTitle());
        log.setUnit(plantGoodsDO.getUnit());
        log.setUpdateUserId(userId);
        plantGoodsLogMapper.insert(log);
        return plantGoodsDO;
    }

    /**
     * 按照时间倒序查询最新20条
     *
     * @return
     * @throws Exception
     */
    @Override
    public Object todayGoods() throws Exception {
        Wrapper<PlantGoodsDO> wrapper = new EntityWrapper<PlantGoodsDO>();
        wrapper.eq("status", 0);
        Integer page = 1;
        Integer limit = 20;
        //时间倒序
        wrapper.orderBy("gmt_create", false);
        Integer count = plantGoodsMapper.selectCount(wrapper);
        List<PlantGoodsDO> PlantGoodsDOS = plantGoodsMapper.selectPage(new RowBounds((page - 1) * limit, limit), wrapper);
        return PlantGoodsDOS;//plantGoodsMapper.getTodayGoodsIndex();
    }

    @Override
    public Object getTodayGoods(Integer page, Integer limit, Long areaId, Long categoryId, String goodName, Double sPrice, Double ePrice) throws Exception {

        Wrapper<PlantGoodsDO> wrapper = new EntityWrapper<PlantGoodsDO>();
        wrapper.eq("status", 0);
        if (areaId != null) {
            wrapper.eq("area_id", areaId);
        }
        if (categoryId != null) {
            wrapper.eq("category_id", categoryId);
        }
        if (goodName != null) {
            wrapper.like("title", goodName);
        }
        if (sPrice != null && ePrice != null) {
            wrapper.between("price", sPrice, ePrice);
        }
        wrapper.orderBy("gmt_create", false);
        Integer count = plantGoodsMapper.selectCount(wrapper);
        List<PlantGoodsDO> PlantGoodsDOS = plantGoodsMapper.selectPage(new RowBounds((page - 1) * limit, limit), wrapper);
        return new Page<>(PlantGoodsDOS, page, limit, count);
    }

    @Override
    public Object plantGoods(Integer page, Integer limit, Long userId) throws Exception {
        page = (page - 1) * page;
        Wrapper<PlantGoodsDO> pgwrapper = new EntityWrapper<>();
        pgwrapper.isNotNull("user_id");
        pgwrapper.last("limit" + page + "," + limit);
        List<PlantGoodsDO> plantGoodsDOS = plantGoodsMapper.selectList(pgwrapper);
        Wrapper<UserShopDO> uswrapper = new EntityWrapper<>();
        uswrapper.isNotNull("user_id");
        List<UserShopDO> userShopDOS = userShopMapper.selectList(uswrapper);
        //Map<String, UserShopDO> userShopDOMap = userShopDOS.stream().collect(Collectors.toMap(UserShopDO::getUserId, Function.identity(), (key1, key2) -> key2));
        List<PlantGoodDetailDTO> detailDTOS = new ArrayList<>();
        for (PlantGoodsDO good : plantGoodsDOS) {
            PlantGoodDetailDTO dto = new PlantGoodDetailDTO();
            //UserShopDO userShopDO = userShopDOMap.get(good.getUserId());
            dto.setPlantGoodsDO(good);
            //dto.setUserShopDO(userShopDO);
            detailDTOS.add(dto);
        }
        return detailDTOS;
    }

    public Object deleteByGoodId(
            Long goodId, Long userId
    ) throws Exception {
        PlantGoodsDO plantGoodsDO = new PlantGoodsDO();
        plantGoodsDO.setStatus(2);
        plantGoodsDO.setId(goodId);
        plantGoodsMapper.updateById(plantGoodsDO);
        return plantGoodsDO;
    }
}
